package models

import (
	"time"
	"user_srv/basic/config"
)

// ChatMessage 聊天消息表：存储用户间的聊天记录
// 表名：chat_message
type ChatMessage struct {
	Id          uint64    `gorm:"column:id;type:bigint UNSIGNED;primaryKey;not null;autoIncrement;" json:"id"`
	MatchId     uint64    `gorm:"column:match_id;type:bigint UNSIGNED;index;not null;comment:匹配ID（会话ID）;" json:"match_id"`
	SenderId    uint64    `gorm:"column:sender_id;type:bigint UNSIGNED;index;not null;comment:发送者ID;" json:"sender_id"`
	ReceiverId  uint64    `gorm:"column:receiver_id;type:bigint UNSIGNED;index;not null;comment:接收者ID;" json:"receiver_id"`
	Content     string    `gorm:"column:content;type:text;not null;comment:消息内容;" json:"content"`
	MessageType int8      `gorm:"column:message_type;type:tinyint(1);default:1;comment:消息类型 1-文本 2-图片 3-语音 4-视频;" json:"message_type"`
	IsRead      int8      `gorm:"column:is_read;type:tinyint(1);default:0;comment:是否已读 0-未读 1-已读;" json:"is_read"`
	CreatedAt   time.Time `gorm:"column:created_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"`
	UpdatedAt   time.Time `gorm:"column:updated_at;type:datetime(3);not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"`
	DeletedAt   time.Time `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

// TableName 返回 ChatMessage 对应的数据库表名："chat_message"
func (ChatMessage) TableName() string {
	return "chat_message"
}

// Create 创建聊天消息
func (c *ChatMessage) Create() error {
	return config.DB.Create(&c).Error
}

// GetByMatchId 根据匹配ID分页获取聊天记录
func (c *ChatMessage) GetByMatchId(matchId uint64, page, pageSize int) ([]ChatMessage, int64, error) {
	var messages []ChatMessage
	var total int64

	if pageSize <= 0 {
		pageSize = 20
	}
	if page <= 0 {
		page = 1
	}

	offset := (page - 1) * pageSize

	// 查询总数
	err := config.DB.Model(&ChatMessage{}).
		Where("match_id = ?", matchId).
		Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	// 查询消息列表（按时间倒序，最新的在前面）
	err = config.DB.Where("match_id = ?", matchId).
		Order("created_at DESC").
		Offset(offset).
		Limit(pageSize).
		Find(&messages).Error

	return messages, total, err
}

// MarkAsRead 标记消息为已读
func (c *ChatMessage) MarkAsRead() error {
	return config.DB.Model(&c).Where("id = ?", c.Id).Update("is_read", 1).Error
}

// MarkMessagesAsReadByMatch 标记某个会话中发给指定用户的所有未读消息为已读
func MarkMessagesAsReadByMatch(matchId, receiverId uint64) error {
	return config.DB.Model(&ChatMessage{}).
		Where("match_id = ? AND receiver_id = ? AND is_read = 0", matchId, receiverId).
		Update("is_read", 1).Error
}

// GetUnreadCount 获取用户的未读消息统计（按会话分组）
func GetUnreadCount(userId uint64) (map[uint64]int64, error) {
	type Result struct {
		MatchId uint64
		Count   int64
	}

	var results []Result
	err := config.DB.Model(&ChatMessage{}).
		Select("match_id, COUNT(*) as count").
		Where("receiver_id = ? AND is_read = 0", userId).
		Group("match_id").
		Find(&results).Error

	if err != nil {
		return nil, err
	}

	unreadMap := make(map[uint64]int64)
	for _, r := range results {
		unreadMap[r.MatchId] = r.Count
	}

	return unreadMap, nil
}

// GetById 根据ID获取消息
func (c *ChatMessage) GetById() error {
	return config.DB.Where("id = ?", c.Id).First(&c).Error
}

// Update 更新消息
func (c *ChatMessage) Update() error {
	return config.DB.Save(&c).Error
}
